package com.xuerhua.yxt.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.xuerhua.yxt.common.enums.UserRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xuerhua.yxt.common.AppUser;
import com.xuerhua.yxt.common.Const;
import com.xuerhua.yxt.common.MenuConst;
import com.xuerhua.yxt.common.RspResult;
import com.xuerhua.yxt.common.enums.RelationType;
import com.xuerhua.yxt.common.enums.Status;
import com.xuerhua.yxt.model.Grid;
import com.xuerhua.yxt.model.StudentLeave;
import com.xuerhua.yxt.page.OrderBy;
import com.xuerhua.yxt.page.Page;
import com.xuerhua.yxt.reqVo.BaseQueryVO;
import com.xuerhua.yxt.reqVo.StudentLeaveReqVO;
import com.xuerhua.yxt.service.IStudentLeaveService;
import com.xuerhua.yxt.service.ITeacherService;
import com.xuerhua.yxt.utils.BeanUtils;
import com.xuerhua.yxt.utils.DateUtil;
import com.xuerhua.yxt.utils.StringUtil;
import com.xuerhua.yxt.view.StudentLeaveView;
import com.xuerhua.yxt.view.TeacherInfoView;
import com.xuerhua.yxt.vo.AuditStudentLeaveReqVO;
import com.xuerhua.yxt.vo.StudentLeaveQueryVO;

@Controller
public class StudentLeaveController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(StudentLeaveController.class);

    @Autowired
    private IStudentLeaveService studentLeaveService;
    @Autowired
    private ITeacherService teacherService;

    /**
     * 老师处理学生请假页
     *
     * @param model
     * @return
     */
    @RequestMapping(Const.TEACHER_ROLE + MenuConst.STUDENT_LEAVE)
    public String studentLeaveToTeacher(Model model) {
        AppUser appUser = getAppUser();
        BaseQueryVO vo = new BaseQueryVO();
        vo.setFinishYear(getCurrentTerm().getFinishYear());
        vo.setId(appUser.getTeacher().getId());
        vo.setSchoolId(appUser.getTeacher().getSchoolId());
        List<TeacherInfoView> teacherInfoView = teacherService.selectClassForTeacher(vo);
        model.addAttribute("model", StringUtil.isNullOrEmpty(teacherInfoView) ? null : teacherInfoView.get(0));
        return "teacher/studentLeave";
    }

    /**
     * 学生请假页面
     *
     * @return
     */
    @RequestMapping(Const.STUDENT_ROLE + MenuConst.LEAVE)
    public String studentLeave(Model model) {
        model.addAttribute("relationType", RelationType.STUDENT_LEAVE.getCode());
        return "student/leave";
    }

    /**
     * 学生新增请假页面
     *
     * @return
     */
    @RequestMapping(Const.STUDENT_ROLE + MenuConst.LEAVE + "/add")
    public String studentLeaveAdd(Model model) {
        model.addAttribute("relationType", RelationType.STUDENT_LEAVE.getCode());
        return "student/addLeave";
    }

    /**
     * 学生请假待审批数据
     */
    @RequestMapping("student/leave/pending")
    @ResponseBody
    Object studentLeavePending(StudentLeaveQueryVO vo) {
        try {
            Page<StudentLeaveView> page = new Page<StudentLeaveView>();
            Grid grid = new Grid();
            List<OrderBy> sorts = new ArrayList<>();
            if (getAppUser().getRoleType() == UserRole.TEACHER.getCode()) {
                vo.setSchoolId(getAppUser().getTeacher().getSchoolId());
            } else {
                vo.setSchoolId(getAppUser().getParent().getSchoolId());
            }
            sorts.add(new OrderBy("CREATE_TIME", "desc"));
            page.setSorts(sorts);
            page.setParams(vo);
            page.setPageNo(vo.getPage());
            page.setPageSize(Integer.MAX_VALUE - 1);
            List<StudentLeaveView> list = studentLeaveService.selectPendingList(page);
            grid.setRows(list);
            grid.setTotal(page.getTotalRecord());
            return grid;
        } catch (Exception e) {
            logger.error("---studentLeavePending error={}", e);
        }
        return null;
    }

    /**
     * 学生请假已审批数据
     *
     * @param vo
     * @return
     */
    @RequestMapping("student/leave/audited")
    @ResponseBody
    Object studentLeaveAudited(StudentLeaveQueryVO vo) {
        try {
            Page<StudentLeaveView> page = new Page<StudentLeaveView>();
            Grid grid = new Grid();
            List<OrderBy> sorts = new ArrayList<>();
            if (getAppUser().getRoleType() == UserRole.TEACHER.getCode()) {
                vo.setSchoolId(getAppUser().getTeacher().getSchoolId());
            } else {
                vo.setSchoolId(getAppUser().getParent().getSchoolId());
            }
            sorts.add(new OrderBy("UPDATE_TIME", "desc"));
            sorts.add(new OrderBy("CREATE_TIME", "desc"));
            page.setSorts(sorts);
            page.setParams(vo);
            page.setPageNo(vo.getPage());
            page.setPageSize(vo.getRows());
            List<StudentLeaveView> list = studentLeaveService.selectAuditedListByPage(page);
            grid.setRows(list);
            grid.setTotal(page.getTotalRecord());
            return grid;
        } catch (Exception e) {
            logger.error("---studentLeaveAudited error={}", e);
        }
        return null;
    }

    /**
     * 学生请假申请
     *
     * @param reqVO
     * @return
     */
    @RequestMapping(Const.STUDENT_ROLE + "/leave/create")
    @ResponseBody
    Object studentLeaveCreate(StudentLeaveReqVO reqVO) {
        try {
            AppUser appUser = getAppUser();
            reqVO.setTermId(getCurrentTerm().getId());
            reqVO.setGrade(appUser.getParent().getGrade());
            reqVO.setClazz(appUser.getParent().getClazz());
            reqVO.setSchoolId(appUser.getParent().getSchoolId());
            reqVO.setSchoolName(appUser.getParent().getSchoolName());
            reqVO.setStudentId(appUser.getParent().getStudentId());
            reqVO.setStudentName(appUser.getParent().getStudentName());
            reqVO.setParentId(appUser.getParent().getId());
            if (reqVO.getIds() != null) {
                reqVO.setIsAttach(1);
            }
            reqVO.setStartTime(DateUtil.strToDate(reqVO.getStartDate(), DateUtil.DEFAULT_DATE_FORMAT1));
            reqVO.setEndTime(DateUtil.strToDate(reqVO.getEndDate(), DateUtil.DEFAULT_DATE_FORMAT1));
            studentLeaveService.insert(reqVO);
            return new RspResult(Status.SUCCESS);
        } catch (Exception e) {
            logger.error("---studentLeaveCreate error={}", e);
        }
        return new RspResult(Status.FAIL);
    }

    /**
     * 老师同意请假
     */
    @RequestMapping(Const.TEACHER_ROLE + "/student/leave/audit")
    @ResponseBody
    Object teacherStudentLeaveAudit(AuditStudentLeaveReqVO reqVO) {
        try {
            AppUser appUser = getAppUser();
            StudentLeave studentLeave = BeanUtils.copyAs(reqVO, StudentLeave.class);
            studentLeave.setUpdateTime(new Date());
            studentLeave.setTeacherId(appUser.getTeacher().getId());
            studentLeave.setTeacherName(appUser.getTeacher().getName());
            int result = studentLeaveService.updateAudit(studentLeave);
            if (result > 0) {
                return new RspResult(Status.SUCCESS);
            }
        } catch (Exception e) {
            logger.error("---teacherStudentLeaveAudit error={}", e);
        }
        return new RspResult(Status.FAIL);
    }

}
